import Constants from '../constants/Constants'
import {EventEmitter} from 'events'
import ajax from '../ajax'

const ActionTypes = Constants.ActionTypes

const EVENT = {
  DELETE: 'DELETE',
  ADD: 'ADD',
  UPDATE: 'UPDATE',
  CHANGE: 'CHANGE'
}

class DataTableStore extends EventEmitter {

  constructor (config, action) {
    super()

    this.columns = config.columns
    this.transport = config.transport
    this.total = 0
    this._ById = {}
    this.data = []

    action.register(action => {

      switch (action.type) {
        case ActionTypes.TABLE_ROW_ADD:
          this.emitAdd(action.data)
          break
        case ActionTypes.TABLE_ROW_DELETE:
          this.emitDelete(action.id)
          break
        case ActionTypes.TABLE_ROW_UPDATE:
          this.emitUpdate(action.data)
          break
      }

    })
  }

  addChangeListener (callback) {
    this.on(EVENT.CHANGE, callback)
  }

  removeListeners (callback) {
    this.removeAllListeners()
  }

  emitChange () {
    this.emit(EVENT.CHANGE)
  }

  addCreateListener (callback) {
    this.on(EVENT.ADD, result => {
      callback && callback(result)
    })
  }

  emitAdd (data) {
    this.create(data, resp => {
      this.emit(EVENT.ADD, resp)
    })
  }

  addRemoveListener (callback) {
    this.on(EVENT.DELETE, result => {
      callback && callback(result)
    })
  }

  emitDelete (id) {
    this.remove(id).done(resp => {
      this.emit(EVENT.DELETE, resp)
    })
  }

  addEditListener (callback) {
    this.on(EVENT.UPDATE, result => {
      callback && callback(result)
    })
  }

  emitUpdate (data) {
    if (data.id && this._ById[data.id]) {
      this.update(data, resp => {
        this._ById[data.id] = data
        this.emit(EVENT.UPDATE, resp)
      })
    }
  }

  setData (resp) {
    this.data = resp.data
    this.total = resp.total

    this.data.forEach(item => {
     this._ById[item.id] = item
    })
  }

  getData () {
    return {
      data: this.data,
      total: this.total
    }
  }

  getUrl (type) {
    return this.transport[type].url || this.transport[type]
  }

  read (data) {
    ajax({
      url: this.getUrl('read'),
      data: {
        page: data.page || 1,
        rows: data.size || 10
      }
    }).done(resp => {
      if (resp && 0 === resp.code) {
        this.setData(resp)
        this.emitChange()
      }
    })
  }

  create (data, callback) {
    return ajax({
      url: this.getUrl('create'),
      data: data
    }, callback)  
  }

  remove (id, callback) {
    return ajax({
      url: this.getUrl('destroy'),
      data: {
        ids: id
      }
    }, callback)
  }

  update (data, callback) {
    return ajax({
      url: this.getUrl('update'),
      data: data
    }, callback)
  }

}

export default DataTableStore

